import { pinyin } from 'pinyin-pro';

export function conversion(data, key , standbyKey) {
  if(!data.length)return { indexList: [], itemArr: [] }
  let indexList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#'];
  let itemArr = Array.from({ length: indexList.length }, () => []);

  data.sort((a, b) => {
    const aFirstPinyin = pinyin(a[key] || a[standbyKey], { toneType: 'none' }).charAt(0).toUpperCase();
    const bFirstPinyin = pinyin(b[key] || b[standbyKey], { toneType: 'none' }).charAt(0).toUpperCase();
    return aFirstPinyin.localeCompare(bFirstPinyin);
  });

  data.forEach((item) => {
    const firstPinyin = pinyin(item[key] || item[standbyKey], { toneType: 'none' }).charAt(0).toUpperCase();
    const groupIndex = indexList.indexOf(firstPinyin) !== -1 ? indexList.indexOf(firstPinyin) : indexList.indexOf('#');
    itemArr[groupIndex].push(item);
  });

  // 筛选出有元素的分组
  const nonEmptyItemArr = itemArr.filter(group => group.length > 0);
  const nonEmptyIndexList = itemArr.reduce((acc, item, index) => {
    if (item.length) acc.push(indexList[index]);
    return acc;
  }, []);
  console.log(nonEmptyIndexList);

  return { indexList: nonEmptyIndexList, itemArr: nonEmptyItemArr };
}